package openfidias.maker.model

import openfidias.maker.format.Formatter as f
import openfidias.maker.clazz.Clazz
import org.apache.commons.lang.StringUtils as sutils

/**
 *
 * @author atila
 */
class Model extends Clazz implements Serializable {

   // list of Attributes objects
   List<Attribute> attributes = []

   String classAttr() {
      if (attributes?.size() == 0){ return "" }

      def source = new StringBuilder()
      attributes.each { attr ->
         source.append(attr.definition())
      }
      source.toString()
   }

   String gettersAndSetters() {
      if (attributes?.size() == 0){ return "" }

      def source = new StringBuilder()
      attributes.each { attr ->
         source.append(attr.getter())
         source.append(attr.setter())
      }
      source.toString()
   }

   String queryCreate() {
      if (attributes?.size() > 0) {
         def s = "INSERT INTO ${_class} ("
         s += attributes.first().name
         attributes.tail().each { attr ->
            s += ", ${attr.name}"
         }
         s += ") VALUES (?"
         if (attributes.size() > 1) {
            s += sutils.repeat(", ?", attributes.size() - 1)
         }
         s += ") RETURNING id"
         return s
      } else {
         // global insert statement
         return "INSERT INTO <table> (<attrs>) VALUES (<values>) RETURNING id"
      }
   }

   String queryDelete() {
      "DELETE FROM ${_class} WHERE id = ?"
   }

   String ps() {
      def s = ""
      def i = 1
      attributes.each { attr ->
         switch( attr.type ) {
            case "String":
               s += "ps.setString(${i}, ${_class}.${attr.getCall()});${f.rt3}"
               break;
            case ["int", "Integer"]:
               s += "ps.setInt(${i}, ${_class}.${attr.getCall()});${f.rt3}"
               break;
            case ["long", "Long"]:
               s += "ps.setLong(${i}, ${_class}.${attr.getCall()});${f.rt3}"
               break;
            case ["double", "Double"]:
               s += "ps.setDouble(${i}, ${_class}.${attr.getCall()});${f.rt3}"
               break;
            case "Date":
               s += "ps.setDate(${i}, ${_class}.${attr.getCall()});${f.rt3}"
               break;
            case "Timestamp":
               s += "ps.setTimestamp(${i}, ${_class}.${attr.getCall()});${f.rt3}"
               break;
         }
         i++
      }
      return s
   }

   /**
    * @deprecated
    */
   String closeBracket() {
      "${f.ret}}${f.ret}"
   }
}

